package com.hl.controller.gouwuche;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.security.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.hl.domain.ShoppingCart;
import com.hl.service.IShoppingCartService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 用户购物车Controller
 *
 * @author ruoyi
 * @date 2025-08-12
 */
@RestController
@RequestMapping("/cart")
public class ShoppingCartController extends BaseController
{
    @Autowired
    private IShoppingCartService shoppingCartService;

    /**
     * 查询用户购物车列表
     */
    // @RequiresPermissions("cart:cart:list")  // 临时注释掉权限验证
    @GetMapping("/list")
    public TableDataInfo list(ShoppingCart shoppingCart)
    {
        // 强制要求memberId参数，确保数据安全
        if (shoppingCart.getMemberId() == null) {
            return new TableDataInfo();
        }
        
        startPage();
        List<ShoppingCart> list = shoppingCartService.selectShoppingCartList(shoppingCart);
        return getDataTable(list);
    }

    /**
     * 导出用户购物车列表
     */
    // @RequiresPermissions("cart:cart:export")  // 临时注释掉权限验证
    @Log(title = "用户购物车", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ShoppingCart shoppingCart)
    {
        List<ShoppingCart> list = shoppingCartService.selectShoppingCartList(shoppingCart);
        ExcelUtil<ShoppingCart> util = new ExcelUtil<ShoppingCart>(ShoppingCart.class);
        util.exportExcel(response, list, "用户购物车数据");
    }

    /**
     * 获取用户购物车详细信息
     */
    // @RequiresPermissions("cart:cart:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        ShoppingCart cart = shoppingCartService.selectShoppingCartById(id);
        if (cart == null) {
            return error("购物车项不存在");
        }
        
        // 验证权限：只能查看自己的购物车
        if (cart.getMemberId() == null) {
            return error("购物车数据异常，无法访问");
        }
        
        return success(cart);
    }

    /**
     * 新增用户购物车
     */
    // @RequiresPermissions("cart:cart:add")  // 临时注释掉权限验证
    @Log(title = "用户购物车", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ShoppingCart shoppingCart)
    {
        // 验证前端传递的memberId是否有效
        if (shoppingCart.getMemberId() == null) {
            return error("用户ID不能为空");
        }
        
        return toAjax(shoppingCartService.insertShoppingCart(shoppingCart));
    }

    /**
     * 修改用户购物车
     */
//    @RequiresPermissions("cart:cart:edit")  // 临时注释掉权限验证
    @Log(title = "用户购物车", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ShoppingCart shoppingCart)
    {
        ShoppingCart existingCart = shoppingCartService.selectShoppingCartById(shoppingCart.getId());
        if (existingCart == null) {
            return error("购物车项不存在");
        }

        // 优先从前端传递的memberId验证权限
        if (shoppingCart.getMemberId() != null) {
            // 验证权限：只能修改自己的购物车项
            if (!shoppingCart.getMemberId().equals(existingCart.getMemberId())) {
                return error("无权限修改此购物车项");
            }
        } else {
            // 如果前端没有传递memberId，则使用SecurityUtils获取
            Long currentUserId = SecurityUtils.getUserId();
            if (currentUserId == null || currentUserId == 0L || !currentUserId.equals(Long.valueOf(existingCart.getMemberId()))) {
                return error("无权限修改此购物车项");
            }
            shoppingCart.setMemberId(currentUserId.intValue());
        }
        
        return toAjax(shoppingCartService.updateShoppingCart(shoppingCart));
    }

    /**
     * 删除用户购物车
     */
    // @RequiresPermissions("cart:cart:remove")  // 临时注释掉权限验证
    @Log(title = "用户购物车", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        //只能删除自己的购物车项
        for (Integer id : ids) {
            //确保数据库表中存在这个数据
            ShoppingCart cart = shoppingCartService.selectShoppingCartById(id);
            if (cart == null) {
                return error("购物车项不存在");
            }
            
            //确保删除的购物车项属于当前用户
            if (cart.getMemberId() == null) {
                return error("购物车数据异常，无法删除");
            }

        }
        
        return toAjax(shoppingCartService.deleteShoppingCartByIds(ids));
    }
}
